package com.wish.business.controller;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wish.base.entity.Business;
import com.wish.base.entity.SysRegion;
import com.wish.base.entity.SysUser;
import com.wish.base.service.IBusinessService;
import com.wish.base.service.ISysRegionService;
import com.wish.base.service.ISysUserService;
import com.wish.business.vo.BusinessVo;
import com.wish.common.core.utils.bean.BeanUtils;
import com.wish.common.redis.service.RedisService;
import com.wish.common.security.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.wish.common.security.annotation.PreAuthorize;
import com.wish.common.core.web.controller.BaseController;
import com.wish.common.core.web.domain.AjaxResult;
import com.wish.common.core.web.page.TableDataInfo;

/**
 * 商户Controller
 * 
 * @author wish
 * @date 2022-05-29
 */
@RestController
@RequestMapping("/business")
public class TbBusinessController extends BaseController
{
    @Autowired
    private IBusinessService iBusinessService;

    @Autowired
    private ISysRegionService sysRegionService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private RedisService redisService;

    private String salt="$2a$10$C24G70GyUlEmi8wk5YWGm.ZIWBADE0GW333uK.dRxh1ypzMVNLiZy";


    /**
     * 查询商户列表
     */
    @PreAuthorize(hasPermi = "system:business:list")
    @GetMapping("/list")
    public TableDataInfo list(Business tbBusiness)
    {
        startPage();
        List<Business> list = iBusinessService.list();
        for (Business business : list) {
//            QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
            SysUser byId = sysUserService.getById(business.getUserId());
            if(null != byId){
                business.setUserName(byId.getUsername());
            }

        }
        return getDataTable(list);
    }

    /**
     * 通过id查询商户表
     */
    @GetMapping(value = "/getBusiness/{id}")
    public AjaxResult getBusiness(@PathVariable("id") Integer id)
    {
        //根据商户id获取商户信息
        Business business = iBusinessService.getById(id);
        //copy属性
        BusinessVo businessVo = new BusinessVo();
        BeanUtils.copyProperties(business,businessVo);

        //根据城市表获取具体城市名称
        if(businessVo.getProvince()!=null){
            SysRegion province = getCityByID(businessVo.getProvince());
            businessVo.setProvinceName(province.getRegionName());
        }
        if(businessVo.getCity()!=null) {
            SysRegion city = getCityByID(businessVo.getCity());
            businessVo.setCityName(city.getRegionName());
        }
        if(businessVo.getCounty()!=null) {
            SysRegion country = getCityByID(businessVo.getCounty());
            businessVo.setCountryName(country.getRegionName());
        }


        //根据用户id获取管理员名称
        if(businessVo.getUserId()!=null){
            SysUser sysUser = sysUserService.getById(businessVo.getUserId());
            businessVo.setUserName(sysUser.getUsername());
        }

        System.err.println(businessVo);
        return AjaxResult.success(businessVo);
    }

    /**
     * 查询城市表
     */
    private SysRegion getCityByID(Integer id){
        SysRegion sysRegion = sysRegionService.getOne(new QueryWrapper<SysRegion>().eq("REGION_ID", id));
        return sysRegion;
    }

    /**
     * 审核通过
     * @return
     */
    @PostMapping("pass/{id}")
    public AjaxResult pass(@PathVariable("id")Integer id){
        //根据id查询
        Business business = iBusinessService.getById(id);
        //修改审核状态
        business.setStatus(1);
        iBusinessService.saveOrUpdate(business);
        return AjaxResult.success();
    }

    /**
     * 审核未通过
     * @return
     */
    @PostMapping("noPass/{id}")
    public AjaxResult noPass(@PathVariable("id")Integer id){
        //根据id查询
        Business business = iBusinessService.getById(id);
        //修改审核状态
        business.setStatus(2);
        iBusinessService.saveOrUpdate(business);
        return AjaxResult.success();
    }

    @GetMapping("/send/{phone}")
    public Object send(@PathVariable("phone") String phone) {
        //随机生成一个四位数字的验证码
        String code = RandomUtil.randomNumbers(4);
        //然后调用业务方法发送短信
            //发送成功，将验证存入到redis缓存中，并设置有效期
            String key = "ymjr:sms:code:"+phone;
        System.out.println(code);
            redisService.setCacheObject(key,code,120L, TimeUnit.SECONDS);
            return AjaxResult.success("短信发送成功");
    }


    /**
     * 获取城市
     * @return
     */
    @GetMapping("getCity")
    public List<SysRegion> getCity(){
        List<SysRegion> provinceList = sysRegionService.list(new QueryWrapper<SysRegion>().eq("PARENT_ID", 1));
        provinceList.forEach(province->{
            //根据省id获取市
            List<SysRegion> cityList = sysRegionService.list(new QueryWrapper<SysRegion>().eq("PARENT_ID", province.getRegionId()));
            province.setChildren(cityList);

            //根据市id获取县
            cityList.forEach(country->{
                //根据省id获取市
                List<SysRegion> countryList = sysRegionService.list(new QueryWrapper<SysRegion>().eq("PARENT_ID", country.getRegionId()));
                country.setChildren(countryList);
            });
        });
        return provinceList;
    }

    @PostMapping("register")
    public AjaxResult register(@RequestBody SysUser user) {
        //根据电话判断是否注册过
        SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("mobile", user.getMobile()));
        if (sysUser!=null) {
            return AjaxResult.error("新增'" + user.getUsername() + "'失败，该账号已被注册");
        }

        String code = redisService.getCacheObject("ymjr:sms:code:"+user.getMobile());
        System.err.println(code);
        if (!code.equals(user.getMsg())) {
            return AjaxResult.error("新增'" + user.getUsername() + "'失败，验证码错误");
        }

        //两次输入的密码不一致
        if (!user.getPassword().equals(user.getRePassword())) {
            return AjaxResult.error("新增'" + user.getUsername() + "'失败，两次输入的密码不一致");
        }

        //密码加密
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        //加盐
        user.setSalt(SecurityUtils.encryptPassword(user.getPassword()+salt));
        user.setCreateTime(LocalDateTime.now());

        //添加账户
        sysUserService.save(user);
        return AjaxResult.success("增加成功",user.getMobile());
    }

    /**
     * 实现完善用户信息以及加入商品表
     * @return
     */
    @PostMapping("registerBusiness")
    public AjaxResult registerBusiness(@RequestBody Business business){
        System.err.println(business);
        //根据电话查询用户
        SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("mobile", business.getMobile()));
        if(sysUser==null){
            return AjaxResult.error("无此用户");
        }

        //添加信息
        iBusinessService.addBusiness(business);

        return AjaxResult.success("完善信息成功");
    }


    /**
     * 获取注册人ip
     * @return
     */
    @GetMapping("getIp")
    public AjaxResult getIp() throws UnknownHostException {
        String hostAddress = InetAddress.getLocalHost().getHostAddress();
        return AjaxResult.success("获取IP成功",hostAddress);
    }


}
